﻿using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;

namespace Qianke.Core.Common
{


    public class HoliDaysHelper : ITransientDependency
    {
        public IAbpLazyServiceProvider LazyServiceProvider { get; set; }
        public class HolidayInfo
        {
            public string name { set; get; }
            public DateTime date { set; get; }

            /// <summary>
            /// 是否为假期
            /// </summary>
            public bool isOffDay { set; get; }
        }


        public async Task<Dictionary<DateTime, HolidayInfo>> GetHoliDays(int year)
        {
            return await LazyServiceProvider.GetRequiredService<IDistributedCache<Dictionary<DateTime, HolidayInfo>>>()
                .GetOrAddAsync($"{year}:HoliDays", async () =>
            {
                var url = $"https://api.jiejiariapi.com/v1/holidays/{year}";
                var httpHepler = new HttpHelper();
                return await httpHepler.Get<Dictionary<DateTime, HolidayInfo>>(url, System.Net.Http.HttpCompletionOption.ResponseContentRead);
            }, () =>
            {
                return new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions()
                {
                    //设置滑动15天过期
                    SlidingExpiration = TimeSpan.FromDays(15)
                };
            });
        }

        public async Task<bool> IsOffDay(DateTime date)
        {
            var holiDays = await GetHoliDays(date.Year);
            if (holiDays.ContainsKey(date.Date))
                return holiDays[date.Date].isOffDay;
            return false;
        }

        public async Task<List<DateTime>> GetWorkDays(DateTime beginTime, DateTime endTime)
        {
            var endDate = endTime.Date;
            var resultList = new List<DateTime>();
            var currentYear = beginTime.Year;
            var holiDays = await GetHoliDays(currentYear);

            for (var curDate = beginTime.Date; curDate <= endDate; curDate = curDate.AddDays(1))
            {
                if (currentYear != curDate.Year)
                {
                    currentYear = curDate.Year;
                    holiDays = await GetHoliDays(currentYear);
                }
                if (!holiDays.ContainsKey(curDate) || !holiDays[curDate.Date].isOffDay)
                    resultList.Add(curDate);
            }
            return resultList;
        }


        public async Task<List<DateTime>> GetWorkDays(DateTime beginTime, DateTime endTime,List<DayOfWeek> weekArray)
        {
            var dateArray = await GetWorkDays(beginTime, endTime);
            return dateArray.Where(u => weekArray.Contains(u.DayOfWeek)).ToList();
        }

    }
}

